﻿using CodeBuilder.Core.Features.Helps;

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Tszy.CodeBuilder.Features;
using Tszy.CodeBuilder.Models;
using Tszy.Unlimited.Base.Extensions;
using Tszy.Unlimited.Data.FreeSQL;

namespace Tszy.CodeBuilder;

internal static class Startup
{
    public static IServiceCollection ConfigureServices(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddScoped<MainExecutor>();
        services.AddScoped<CodeExecutor>();
        services.RegisterConfigs(configuration);
        services.RegisterDatabase();

        return services;
    }

    internal static void Execute(IServiceProvider serviceProvider, string[] args)
    {
        Console.WriteLine("请输入“help”查看指令列表!");

        while (true)
        {
            var command = Console.ReadLine() ?? string.Empty;

            // 清除空格。
            command = command.Trim().Trim('　').Trim().Trim('@').ToLower();

            ExecuteHelp(command);

            using IServiceScope scope = serviceProvider.CreateScope();

            var scopedProcessingService = scope.ServiceProvider.GetRequiredService<MainExecutor>();

            scopedProcessingService.Execute(scope.ServiceProvider, command);
        }
    }

    private static void ExecuteHelp(string command)
    {
        GetHelp.ExecuteHelp(command);
    }
}

internal static class ConfigurationExtensionsMethods
{
    /// <summary>
    /// 配置设置信息。
    /// </summary>
    /// <param name="services"></param>
    /// <param name="configuration"></param>
    public static IServiceCollection RegisterConfigs(this IServiceCollection services, IConfiguration configuration)
    {
        //初始化配置信息。
        SettingData.Initialize(configuration.Get<SettingData>());

        return services;
    }

    public static IServiceCollection RegisterDatabase(this IServiceCollection services)
    {
        if (SettingData.Instance?.Database == null)
            return services;

        //初始化 Linq 数据组件。
        var connectionString = SettingData.Instance.Database.DbConnection ?? string.Empty;

        if (!string.IsNullOrWhiteSpace(SettingData.Instance.Database.DbKey))
        {
            connectionString = connectionString.AES32Decrypt(SettingData.Instance.Database.DbKey);
        }

        services.RegisterFreeSQLDotMySQL(connectionString);

        return services;
    }
}